#include<iostream>
#include<list>
using namespace std;


class Solution {
public:
	int LastRemaining_Solution(int n, int m)
	{
		int tmp = m;
		list<int> l;
		for (int i = 0; i < n; i++)
		{
			l.push_back(i);
		}
		list<int>::iterator it = l.begin();
		while (l.size() > 1)
		{
			tmp = m;
			while (--tmp)
			{
				it++;
				if (it == l.end())
				{
					it = l.begin();
				}
			}
			it = l.erase(it);
			if (it == l.end())
			{
				it = l.begin();
			}
		}
		return *it;
	}
};

int main()
{
	Solution s;
	cout<<s.LastRemaining_Solution(5, 3);
	return 0;
}